<template>
  <section class="f-agents">
    <div class="w-card my-content-box">
      <div class="title-box">
        <span class="title-text">代理商库存详情</span>
        <ul class="f-title-desc">
          <li>
            <p>代理商：</p>
            <p>{{queryForm.shopName}}</p>
          </li>
          <li>
            <p>设备商品ID：</p>
            <p>{{queryForm.wareGoodsId}}</p>
          </li>
          <li>
            <p>设备型号：</p>
            <p>{{queryForm.equipmentType}}</p>
          </li>
        </ul>
        <div style="margin-left:auto;">
          <!-- <el-button @click="importHandle()">导入</el-button> -->
          <el-button @click="exportHandle()" type="warning" plain>导出</el-button>
        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>编号：</span>
          <el-input v-model="searchForm.deviceNo" clearable placeholder="请输入编号" />
        </div>
        <div>
          <span>ICCID：</span>
          <el-input v-model="searchForm.iccid" clearable placeholder="请输入ICCID" />
        </div>
        <div>
          <span>短号：</span>
          <el-input v-model="searchForm.shortNo" clearable placeholder="请输入短号" />
        </div>
        <div>
          <span>激活状态：</span>
          <el-select v-model="searchForm.activeFlag" clearable>
            <el-option label="已激活" value="1" />
            <el-option label="未激活" value="0" />
            <el-option label="退货" value="3" />
          </el-select>
        </div>
        <div class="f-ml-20">
          <el-button @click="searchHandle" type="primary">查询</el-button>
          <el-button @click="resetHandle">重置</el-button>
        </div>
      </div>

      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" stripe @selection-change="selectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column prop="deviceId" label="设备ID" align="center">
            <template v-slot="scope">
              {{ scope.row.deviceId || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="deviceNo" label="编号" align="center">
            <template v-slot="scope">
              {{ scope.row.deviceNo || '--' }}
            </template>
          </el-table-column>
          <el-table-column prop="iccid1" label="ICCID&短号(1)" align="center">
            <template v-slot="scope">
              <p>ICCID：{{ scope.row.iccid1 || '--' }}</p>
              <p>短号：{{ scope.row.shortNo1 || '--' }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="iccid2" label="ICCID&短号(2)" align="center">
            <template v-slot="scope">
              <p>ICCID：{{ scope.row.iccid2 || '--' }}</p>
              <p>短号：{{ scope.row.shortNo2 || '--' }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="iccid3" label="ICCID&短号(3)" align="center">
            <template v-slot="scope">
              <p>ICCID：{{ scope.row.iccid3 || '--' }}</p>
              <p>短号：{{ scope.row.shortNo3 || '--' }}</p>
            </template>
          </el-table-column>
          <el-table-column prop="activeFlag" label="激活状态" align="center">
            <template v-slot="scope">
              {{ activeFlag[scope.row.activeFlag]  }}
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="入库时间" align="center">
            <template v-slot="scope">
              {{ scope.row.createDate || '--' }}
            </template>
          </el-table-column>
        </el-table>
        <div class="my-table-footer">
          <div class="footer_btn_box">
            <el-button :disabled="chooseList.length == 0" @click="settingHandle" type="warning" size="small"
              plain>批量回拨</el-button>
          </div>
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <!-- 导入弹窗 -->
    <Upload ref="uploadRef" v-if="off.upload" :uploadForm="uploadForm" @handleUploadSuccess="importSuccess"
      @handleUploadCancel="handleUploadCancel" />

    <!-- 回拨弹窗 -->
    <el-dialog v-model="off.dialog" title="设备回拨" width="600">
      <el-form ref="dialogFormRef" :model="dialogForm" :rules="dialogRules">
        <el-form-item prop="fromShopId" label="来源代理商">
          <el-input v-model="queryForm.shopName" readonly></el-input>
        </el-form-item>
        <el-form-item prop="toShopId" label="目标代理商">
          <el-input v-model="toShopName" readonly></el-input>
        </el-form-item>
        <el-form-item prop="businessTime" label="操作时间">
          <el-date-picker v-model="dialogForm.businessTime" type="datetime" value-format="x" placeholder="请选择日期时间" />
        </el-form-item>
        <el-form-item prop="remarks" label="备注">
          <el-input v-model="dialogForm.remarks" :rows="3" type="textarea" placeholder="请输入备注..." />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogCancel()">取消</el-button>
          <el-button type="primary" @click="dialogSave()">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 确认密码 -->
    <ConfirmPass ref="confirmPasswordRef" @verification="confirmSuccess" />

    <router-view></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch, nextTick } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRoute, useRouter } from 'vue-router'
import Upload from '@/components/Upload.vue'
import ConfirmPass from '@/components/confirmPass.vue'
import api from '../api'

export default {
  components: { Upload, ConfirmPass },

  setup() {
    const route = useRoute()
    const router = useRouter()

    const uploadRef = ref(null)
    const confirmPasswordRef = ref(null)
    const dialogFormRef = ref(null)

    const state = reactive({
      off: {
        upload: false,
        dialog: false,
      },
      isDetail: false,

      searchForm: {
        "activeFlag": "",
        "createTimeMax": "",
        "createTimeMin": "",
        "deviceNo": "",
        "iccid": "",
        "orderBy": "id desc",
        "shopId": route.query.shopId,
        "shortNo": "",
        "updateTimeMax": "",
        "updateTimeMin": "",
        "wareGoodsId": route.query.wareGoodsId
      },

      tableHeight: 0,
      tableData: [],
      page: 1,
      size: 10,
      total: 0,

      chooseList: [],
      shopList: [],
      activeFlag: {
        '0': '未激活',
        '1': '已激活',
        '3': '退货',
      },

      uploadForm: {
        dialogTitle: '导入加盟订单',
        action: '/eas/manage/order/join/upload'
      },

      queryForm: {},

      toShopName: '平台',
      dialogForm: {},
      dialogRules: {
        businessTime: [
          { required: true, message: '请选择操作时间', trigger: 'change' },
        ],
      },
    })

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {
        "activeFlag": "",
        "createTimeMax": "",
        "createTimeMin": "",
        "deviceNo": "",
        "iccid": "",
        "orderBy": "id desc",
        "shopId": route.query.shopId,
        "shortNo": "",
        "updateTimeMax": "",
        "updateTimeMin": "",
        "wareGoodsId": route.query.wareGoodsId
      }
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
      }
      api.deptDeviceList(obj).then(res => {
        state.tableData = res.data.list
        state.total = res.data.total
      }).catch(err => {
        console.log(err)
      })
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    // 导出
    const exportHandle = () => {
      const obj = {
        responseType: 'blob',
        ...state.searchForm,
      }
      api.deptDeviceExport(obj).then(res => {
        const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
        BlobDownLoad(res, _fileName)
      }).catch(err => {
        console.log(err)
      })
    }

    // 导入
    function importHandle() {
      state.off.upload = true
      nextTick(() => {
        uploadRef.value.off.dialog = true
      })
    }

    //导入成功
    function importSuccess() {
      state.page = 1
      getTableData()
    }

    const handleUploadCancel = () => {
      state.off.upload = false
    }

    function settingHandle() {
      if (state.chooseList.length == 0) {
        return
      }

      state.off.dialog = true
      // const title = "提示"
      // const msg = '您确定要将所选的设备回拨吗？'
      // confirmPasswordRef.value.dialogShow(title, msg)
    }

    const confirmSuccess = () => {

    }

    function selectionChange(list) {
      state.chooseList = list
    }

    const getShopList = () => {
      api.shopList().then(res => {
        state.shopList = res.data.list
      })
    }

    const dialogCancel = () => {
      state.off.dialog = false
      state.dialogForm = {}
      dialogFormRef.value.resetFields()
    }

    const dialogSave = () => {
      dialogFormRef.value.validate((valid, fields) => {
        if (valid) {
          let json = {
            "businessTime": state.dialogForm.businessTime,
            "fromShopId": state.queryForm.shopId,
            "list": [],
            "remarks": state.dialogForm.remarks || '',
            "toShopId": "system"
          }

          state.chooseList.forEach(item => {
            let obj = {
              "deviceId": item.deviceId,
              "deviceNo": item.deviceNo
            }
            json.list.push(obj)
          })
          api.shouhuiSubmit(json).then(res => {
            successDeal('操作成功！')
            getTableData()
            dialogCancel()
          })
        }
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 280
      state.queryForm = route.query
      console.log(state.queryForm)
      getTableData()
      getShopList()
    })

    return {
      ...toRefs(state),
      uploadRef,
      confirmPasswordRef,
      dialogFormRef,
      searchHandle,
      resetHandle,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      exportHandle,
      importSuccess,
      importHandle,
      handleUploadCancel,
      settingHandle,
      confirmSuccess,
      selectionChange,
      dialogCancel,
      dialogSave,
    }
  }
}
</script>

<style lang="scss" scoped>
.f-agents {
  .my-content-box {
    box-sizing: border-box;
    padding: 20px;

    .title-box {
      display: flex;
      align-items: center;

      .title-text {
        font-size: 16px;
        font-weight: bold;
      }
    }

    .f-title-desc {
      display: flex;
      align-items: center;
      font-size: 14px;
      margin-left: 40px;
      gap: 0 40px;
      li {
        display: flex;
        align-items: center;
        p:first-child {
          color: #707070;
        }
      }
    }

    .my-search-box {
      box-sizing: border-box;
      padding: 20px 20px 20px 0;
      padding-bottom: 0;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 10px;

      > div {
        width: 300px;
        display: flex;
        align-items: center;

        > span {
          flex-shrink: 0;
          width: 90px;
          text-align: right;
        }
      }

      .datebox {
        width: 400px;
      }
    }

    .my-table-box {
      margin-top: 20px;

      .table-handle-box {
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .my-table-footer {
        display: flex;
        align-items: center;
        margin-top: 10px;
        flex-wrap: wrap;
        gap: 10px;
      }
    }
  }
}
</style>